﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Proggy.Web.Cms.PropertyTypes;
using Proggy.Web.Cms.Core.Configuration.ConfigObjects;
using Proggy.Web.Cms.Core.Models;
using Newtonsoft.Json;

namespace Proggy.Web.Cms.Core.PropertyTypes
{
    /// <summary>
    /// Select url/s
    /// </summary>
    [PropertyType("Related pages", "~/Areas/ProggyCore/Views/EditorPartials/UrlSelectorEditor.cshtml", RequiredConfigObjectType = typeof(UrlSelectorConfigObject))]
    public class UrlSelector : ConfigurablePropertyTypeBase, IValidatablePropertyType, IAutoRenderPropertyType
    {
        /// <summary>
        /// Constructor
        /// </summary>
        public UrlSelector()
        {
            if (this.AddedUrl == null)
            {
                this.AddedUrl = new AddedUrl
                {
                    UrlType = AddedUrlType.Internal
                };
            }
        }

        #region properties

        /// <summary>
        /// Main property
        /// </summary>
        public AddedUrl AddedUrl { get; set; }

        #endregion

        #region inteface

        public Tuple<bool, string> GetIsValid(System.ComponentModel.DataAnnotations.ValidationContext vContext, ContentModel.ContentModelPropertyTypeAttribute attr)
        {
            // get config object
            var configObject = this.GetConfigObjectInValidationContext<UrlSelectorConfigObject>(vContext, attr);

            // 
            return this.GetIsValidFromConfigObject(configObject);
        }

        public Tuple<bool, string> GetIsValidFromConfigObject(UrlSelectorConfigObject configObject)
        {
            // 
            if (configObject.LinkIsMandatory)
            {

                //
                if (this.AddedUrl.UrlType == AddedUrlType.Internal && this.AddedUrl.NodeId == null && configObject.LinkIsMandatory)
                {
                    return new Tuple<bool, string>(false, "If you select \"Site link\" you must chose a content node");
                }


                //
                if (configObject.RequireLinkTitle && this.AddedUrl != null && string.IsNullOrEmpty(this.AddedUrl.LinkTitle))
                {
                    return new Tuple<bool, string>(false, "Link title is required");
                }
            }

            //
            return new Tuple<bool, string>(true, "");
        }

        public object GetAutoRenderModel()
        {
            return this;
        }

        [JsonIgnore]
        public string FullPathToAutoRenderPartial
        {
            get { return "~/Areas/ProggyCore/Views/AutoRenderPartials/_UrlSelector.cshtml"; }
        }

        #endregion
    }
}
